from rest_framework import serializers
from .models import *
from django.contrib.auth.hashers import make_password

class UserSerializer(serializers.Serializer):
    username = serializers.CharField()
    password = serializers.CharField()
    mobile = serializers.CharField()
    weixinid = serializers.CharField()
    email = serializers.CharField()
    def create(self, data):
        password = data.pop('password')
        user = User.objects.create(**data)
        user.password = make_password(password)
        user.save()
        return user

class RoleSerializer(serializers.Serializer):
    zh_name = serializers.CharField()
    name = serializers.CharField()
    description = serializers.CharField()
    def create(self, data):
        return Role.objects.create(**data)


class DeparSerializer(serializers.Serializer):
    name = serializers.CharField()
    fid_id = serializers.IntegerField()
    def create(self, data):
        print('----')
        if data['fid_id'] > 0:
            return Department.objects.create(**data)
        fid = data.pop('fid_id')
        dep = Department.objects.create(**data)
        return dep

class RoleModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = Role
        fields = ['id','zh_name']

class DeparModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = Department
        fields = ['name','id']


class UserModelSerializer(serializers.ModelSerializer):
    role = RoleModelSerializer(many=True)
    department_set = DeparModelSerializer(many=True)
    class Meta:
        model = User
        fields = '__all__'








